<template xmlns="http://www.w3.org/1999/html">
  <div class="modal modal-blur fade" id="modal-add-plugin" tabindex="-1" role="dialog" aria-hidden="true"
       ref="addPluginModalRef">
    <div class="modal-dialog modal-lg modal-dialog-centered" role="document">
      <div class="modal-content">
        <form id="addPluginForm" class="needs-validation" novalidate @submit.prevent="submitForm">
          <div class="modal-header">
            <h5 class="modal-title">新增插件</h5>
            <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
          </div>
          <div class="modal-body">
            <div class="mb-3">
              <label class="form-label required">插件名称</label>
              <input type="text" 
                     class="form-control" 
                     name="name" 
                     placeholder="请输入插件名称"
                     maxlength="30"
                     required>
              <div class="invalid-feedback">
                请输入插件名称
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">版本号</label>
              <input type="text" 
                     class="form-control" 
                     name="version" 
                     placeholder="请输入版本号"
                     maxlength="30"
                     required>
              <div class="invalid-feedback">
                请输入版本号
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label required">文件类型</label>
              <select class="form-select" 
                      id="fileType" 
                      name="fileType" 
                      required>
                <option value="">请选择文件类型</option>
                <option value="residentPlugin">residentPlugin</option>
                <option value="manager">manager</option>
                <option value="setup">setup</option>
              </select>
              <div class="invalid-feedback">
                请选择文件类型
              </div>
            </div>
            <div class="mb-3">
              <label class="form-label">上传路径</label>
              <input type="text" 
                     class="form-control" 
                     name="path" 
                     placeholder="请输入上传路径"
                     maxlength="100">
            </div>
            <div class="mb-3">
              <label class="form-label">备注</label>
              <textarea class="form-control" 
                        id="remark" 
                        name="remark" 
                        placeholder="请输入备注"
                        maxlength="100"
                        rows="3"></textarea>
              <div class="text-muted small">最多输入100个字符</div>
            </div>
            <div class="mb-3">
              <label class="form-label required">上传插件文件</label>
              <input type="file" 
                     class="form-control" 
                     id="pluginFile" 
                     name="pluginFile"
                     required>
              <div class="invalid-feedback">
                请选择插件文件
              </div>
            </div>
          </div>
          <div class="modal-footer">
            <button type="button" 
                    class="btn btn-link link-secondary" 
                    data-bs-dismiss="modal">
              取消
            </button>
            <button type="submit" 
                    class="btn btn-primary ms-auto">
              保存
            </button>
          </div>
        </form>
      </div>
    </div>

  </div>

  <ComponentModal
      :title="'信息'"
      :message="'操作成功'"
      :cancelText="'取消'"
      :confirmText="'确定'"
      ref="componentModalOutRef"
  />

  <Loading ref="loadingRef"/>

</template>

<style scoped>
/* 必填项样式 */
.required:after {
  content: " *";
  color: red;
}

/* 表单验证样式 */
.was-validated .form-control:invalid,
.was-validated .form-select:invalid {
  border-color: #dc3545;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 12 12' width='12' height='12' fill='none' stroke='%23dc3545'%3e%3ccircle cx='6' cy='6' r='4.5'/%3e%3cpath stroke-linejoin='round' d='M5.8 3.6h.4L6 6.5z'/%3e%3ccircle cx='6' cy='8.2' r='.6' fill='%23dc3545' stroke='none'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.was-validated .form-control:valid,
.was-validated .form-select:valid {
  border-color: #198754;
  padding-right: calc(1.5em + 0.75rem);
  background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 8 8'%3e%3cpath fill='%23198754' d='M2.3 6.73L.6 4.53c-.4-1.04.46-1.4 1.1-.8l1.1 1.4 3.4-3.8c.6-.63 1.6-.27 1.2.7l-4 4.6c-.43.5-.8.4-1.1.1z'/%3e%3c/svg%3e");
  background-repeat: no-repeat;
  background-position: right calc(0.375em + 0.1875rem) center;
  background-size: calc(0.75em + 0.375rem) calc(0.75em + 0.375rem);
}

.invalid-feedback {
  display: none;
  width: 100%;
  margin-top: 0.25rem;
  font-size: 0.875em;
  color: #dc3545;
}

.was-validated .form-control:invalid ~ .invalid-feedback,
.was-validated .form-select:invalid ~ .invalid-feedback {
  display: block;
}
</style>

<script setup>
import {defineExpose, nextTick, onMounted, ref} from "vue";
import {Modal} from "bootstrap";
import ComponentModal from "@/components/ComponentModal.vue";
import Loading from "@/components/Loading.vue";

const addPluginModalRef = ref(null);
const componentModalOutRef = ref(null);
const loadingRef = ref(null);

let modalInstance = null;
const apiBaseUrl = import.meta.env.VITE_API_BASE_URL;

// 在组件挂载时初始化 Bootstrap 的 Modal
onMounted(() => {
  if (addPluginModalRef.value) {
    modalInstance = new Modal(addPluginModalRef.value);
  }
});

const submitForm = async (event) => {
  const form = document.getElementById("addPluginForm");
  
  // 添加验证样式类
  form.classList.add('was-validated');
  
  // 检查表单是否有效
  if (!form.checkValidity()) {
    return; // 如果验证失败，直接返回，不关闭模态框
  }

  const formData = new FormData(form);
  const url = `${apiBaseUrl}/resident/plugin/add`;

  loadingRef.value.openLoading();

  try {
    const response = await fetch(url, {
      method: 'POST',
      body: formData
    });
    const data = await response.json();
    
    if (data.success) {
      componentModalOutRef.value.openInfoModal('添加成功！');
      // 重置表单验证状态
      form.classList.remove('was-validated');
      form.reset();
      // 成功后才关闭模态框
      modalInstance.hide();
      location.reload();
    } else {
      componentModalOutRef.value.openWarnModal("插件新增失败：" + data.errorMsg);
    }
  } catch (error) {
    componentModalOutRef.value.openWarnModal('插件新增失败，请稍后重试！');
  } finally {
    loadingRef.value.closeLoading();
  }
};

// 打开模态框
const openModal = () => {
  if (modalInstance) {
    modalInstance.show();
  }
};

const closeModal = () => {
  if (modalInstance) {
    modalInstance.hide();
  }
};

defineExpose({
  openModal, closeModal
});

</script>